import java.io.*;
import java.util.regex.*;

public class TemplateManipulator {

	static public String htmlFile;

    /**
	  * Fetch the entire contents of a text file, and return it in a String.
	  * This style of implementation does not throw Exceptions to the caller.
	  *
	  * @param aFile is a file which already exists and can be read.
	  */
	  static public String getContents(File aFile) {
	    //...checks on aFile are elided
	    StringBuffer contents = new StringBuffer();
	    
	    try {
	      //use buffering, reading one line at a time
	      //FileReader always assumes default encoding is OK!
	      BufferedReader input =  new BufferedReader(new FileReader(aFile));
	      try {
	        String line = null; //not declared within while loop
	        /*
	        * readLine is a bit quirky :
	        * it returns the content of a line MINUS the newline.
	        * it returns null only for the END of the stream.
	        * it returns an empty String if two newlines appear in a row.
	        */
	        while (( line = input.readLine()) != null){
	          contents.append(line);
	          contents.append(System.getProperty("line.separator"));
	        }
	      }
	      finally {
	        input.close();
	      }
	    }
	    catch (IOException ex){
	      ex.printStackTrace();
	    }

	    return contents.toString();
	  }

	  /**
	  * Change the contents of text file in its entirety, overwriting any
	  * existing text.
	  *
	  * This style of implementation throws all exceptions to the caller.
	  *
	  * @param aFile is an existing file which can be written to.
	  * @throws IllegalArgumentException if param does not comply.
	  * @throws FileNotFoundException if the file does not exist.
	  * @throws IOException if problem encountered during write.
	  */
	  static public void setContents(File aFile, String aContents)
	                                 throws FileNotFoundException, IOException {
	    if (aFile == null) {
	      throw new IllegalArgumentException("File should not be null.");
	    }
	    if (!aFile.exists()) {
	      throw new FileNotFoundException ("File does not exist: " + aFile);
	    }
	    if (!aFile.isFile()) {
	      throw new IllegalArgumentException("Should not be a directory: " + aFile);
	    }
	    if (!aFile.canWrite()) {
	      throw new IllegalArgumentException("File cannot be written: " + aFile);
	    }

	    //use buffering
	    Writer output = new BufferedWriter(new FileWriter(aFile));
	    try {
	      //FileWriter always assumes default encoding is OK!
	      output.write( aContents );
	    }
	    finally {
	      output.close();
	    }
	  }
	
    static public String escapeHtml(String str) {
        str = replaceString(str,"&","&amp;");
        str = replaceString(str,"<","&lt;");
        str = replaceString(str,">","&gt;");
        str = replaceString(str,"\"","&quot;");
        str = replaceString(str,"'","&apos;");
        return str;
    }  

    static public String replaceString(String text, String repl, String with) {
        return replaceString(text, repl, with, -1);
    }

    /**
     * Replace a string with another string inside a larger string, for
     * the first n values of the search string.
     *
     * @param text String to do search and replace in
     * @param repl String to search for
     * @param with String to replace with
     * @param n    int    values to replace
     *
     * @return String with n values replaced
     */
    static public String replaceString(String text, String repl, String with, int max) {
        if(text == null) {
            return null;
        }
 
        StringBuffer buffer = new StringBuffer(text.length());
        int start = 0;
        int end = 0;
        while( (end = text.indexOf(repl, start)) != -1 ) {
            buffer.append(text.substring(start, end)).append(with);
            start = end + repl.length();
 
            if(--max == 0) {
                break;
            }
        }
        buffer.append(text.substring(start));
 
        return buffer.toString();
    }
    
    static public String getTaggedHTML(String tagName) {
    	String startTag = "<EZLISTINGPAGE name=" + tagName + ">";
    	String endTag = "</EZLISTINGPAGE>";
        String patternStr = startTag + "*" + endTag;
        String taggedHTML;
        
        // Compile the regular expression
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(htmlFile);

        // Find the first occurence of the matching pattern
        if (matcher.find()) {
            // Get the match result
        	taggedHTML = new String(matcher.group());
        }
        else {
        	throw new PatternSyntaxException("Can not find pattern!", patternStr, -1);
        }

        // We only want to find one match
        if (matcher.find()) {
        	throw new PatternSyntaxException("Found another pattern!", patternStr, -1);
        }
        
        // Throw away the tags
        String nobeginningtagtaggedHTML = taggedHTML.replaceAll(startTag, "");
        String nonTaggedHTML = nobeginningtagtaggedHTML.replaceAll(endTag, "");
        
        // Return the result
        return nonTaggedHTML;
    }
    
    static public boolean setTaggedHTML(String tagName, String tagValue) {
    	String startTag = "<EZLISTINGPAGE name=" + tagName + ">";
    	String endTag = "</EZLISTINGPAGE>";
    	String replaceStr = startTag + tagValue + endTag;
    	String patternStr = startTag + "*" + endTag;

        // Compile the regular expression
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(htmlFile);
        
        // Find and replace all occurences of the matching pattern
        boolean found = false;
        if (found = matcher.find()) {
        	htmlFile = new String(matcher.replaceAll(replaceStr));
        }

        // Return the result
        return found;
    }
    
    /** Simple test harness.   */
    static public void main (String... aArguments) throws IOException {
      File templateFile = new File("F:\\My Homework\\Intelligent User Interfaces\\EZ Listing Page\\src\\template.html");
      htmlFile = new String(getContents(templateFile));
      if (setTaggedHTML("MainArtPicture", "<IMG SRC=\"http://users.wpi.edu/~dobosz/Ebay/Magdalena's_Art_Studio.jpeg\" ALT=\"Magdalena's Art Studio\" WIDTH=700 HEIGHT=175>")) {
    	  setContents(templateFile, htmlFile);
      }
    }
}
